﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BusinessPlatform.Core.Database;
using System.IO;
using System.Xml;
using BusinessPlatformTool.Parser;
using BusinessPlatformTool.CodeFiles;
using BusinessPlatformTool.DatabaseSQL;

namespace BusinessPlatformTool
{
    public partial class ConfigureTools : Form
    {
        IDatabase db;
        public ConfigureTools()
        {
            InitializeComponent();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                db = DatabaseFactory.CreateDatabase();
                db.DbName = "master";
                gpbDatabaseSetting.Enabled = true;
                gpbSystemTable.Enabled = true;
                gpbBusinessObjectTable.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void btnDialag_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtDatabaseName.Text))
                {
                    MessageBox.Show("缺少数据库名");
                    return;
                }
                FolderBrowserDialog Dialog = new FolderBrowserDialog();
                if (Dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    txtDatabasePath.Text = Dialog.SelectedPath;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void CreateSystemTable(string TextPath)
        {
            try
            {
                var TSQL = File.OpenText(TextPath + "SystemTable.txt").ReadToEnd();
                db.BeginTransaction();
                foreach (var SQL in TSQL.Split(new string[] { "go" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    db.ExceuteNonQuery(SQL);
                }
                db.EndTranscation(TransactionOptions.Commit);
                status.Items["statusText"].Text = "创建系统表 Successful！";
            }
            catch (Exception ex)
            {
                db.EndTranscation(TransactionOptions.Rollback);
                throw (ex);
            }
        }
        private void btnCreateDatabase_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtDatabaseName.Text))
                {
                    MessageBox.Show("缺少数据库名");
                    return;
                }
                if (string.IsNullOrEmpty(txtDatabasePath.Text))
                {
                    MessageBox.Show("缺少数据库路径");
                    return;
                }
                string TextPath = Application.StartupPath + "\\" + "T-SQLText\\";
                #region 创建数据库
                string TSQL = File.OpenText(TextPath + "CreateDatabase.txt").ReadToEnd();
                TSQL = string.Format(TSQL, txtDatabaseName.Text, txtDatabasePath.Text);
                foreach (var SQL in TSQL.Split(new string[] { "go" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    db.ExceuteNonQuery(SQL);
                }
                status.Items["statusText"].Text = "数据库创建 Successful！";
                #endregion
                #region 创建系统表
                if (chkSystemTable.Checked)
                {
                    CreateSystemTable(TextPath);
                }
                #endregion
                MessageBox.Show("Successful");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void btnCreateSystemTable_Click(object sender, EventArgs e)
        {
            try
            {
                CreateSystemTable(Application.StartupPath + "\\" + "T-SQLText\\");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private string GetDialgPath()
        {
            FileDialog dialog = new OpenFileDialog();
            dialog.Filter = "xml|*.xml";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                return dialog.FileName;
            return "";
        }
        private void btnXmlFileDialog_Click(object sender, EventArgs e)
        {
            try
            {
                txtXmlPath.Text = GetDialgPath();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private XmlDocument CheckXmlSetting(string XmlPath)
        {
            #region 检查XML配置
            XmlDocument xml = new XmlDocument();
            xml.Load(XmlPath);
            //"//databind[@table!=''][@alias!='']/parent::*/parent::*[@visible!='0']";
            string xpath = "//Table[@Name=''][@Type=''][@ClassName='']";
            if (xml.SelectNodes(xpath).Count > 0)
            {
                MessageBox.Show("数据结构有问题，检查数据表的信息。");
                return null;
            }
            xpath = "//Field[@Name=''][@DbType=''][@PropertyName='']";
            if (xml.SelectNodes(xpath).Count > 0)
            {
                MessageBox.Show("数据结构有问题，检查字段的信息。");
                return null;
            }
            xpath = "//Object[@ObjectType=''][@ObjectCode=''][@NameSapace='']";
            if (xml.SelectNodes(xpath).Count > 0)
            {
                MessageBox.Show("数据结构有问题，检查对象的信息。");
                return null;
            }
            //xpath = "//Table[@Name:count()>1]";
            //if (xml.SelectNodes(xpath).Count > 0)
            //{
            //    MessageBox.Show("数据结构有问题，检查对象的信息。");
            //}
            #endregion
            return xml;
        }
        private void btnCreateBusinessTable_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtXmlPath.Text))
                {
                    MessageBox.Show("文件名为空！");
                    return;
                }
                var xml = CheckXmlSetting(txtXmlPath.Text);
                if (xml == null)
                    return;
                DataStructureParser Parser = new DataStructureParser();
                Parser.ShowErrorMessageEvent += new ShowErrorMessage(Parser_ShowErrorMessageEvent);
                if (Parser.Parser(xml) == false) return;
                var QueryList = CreateSQL.GetQueryString(Parser.BO);
                db.BeginTransaction();
                foreach (var Query in QueryList)
                {
                    db.ExceuteNonQuery(Query);
                }
                db.EndTranscation(TransactionOptions.Commit);
                status.Items["statusText"].Text = "业务表 Successful！";
            }
            catch (Exception ex)
            {
                db.EndTranscation(TransactionOptions.Rollback);
                MessageBox.Show(ex.Message);
            }
        }

        void Parser_ShowErrorMessageEvent(string ErrorMessage)
        {
            MessageBox.Show(ErrorMessage);
        }

        private void btnSettingDialog_Click(object sender, EventArgs e)
        {
            try
            {
                txtSettingFile.Text = GetDialgPath();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnCreateBOFiles_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtSettingFile.Text))
                {
                    MessageBox.Show("文件名为空！");
                    return;
                }
                var xml = CheckXmlSetting(txtSettingFile.Text);
                if (xml == null)
                    return;
                DataStructureParser Parser = new DataStructureParser();
                Parser.ShowErrorMessageEvent += new ShowErrorMessage(Parser_ShowErrorMessageEvent);
                if (Parser.Parser(xml) == false) return;
                CreateCodeFiles.CreateEnum(Parser.DicValidDataType, txtLocation.Text);
                CreateCodeFiles.CreateFiles(Parser.BO, txtLocation.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnLocationDialog_Click(object sender, EventArgs e)
        {
            try
            {
                FolderBrowserDialog Dialog = new FolderBrowserDialog();
                if (Dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    txtLocation.Text = Dialog.SelectedPath;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void CreateWinFormFiles_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtSettingFile.Text))
                {
                    MessageBox.Show("文件名为空！");
                    return;
                }
                var xml = CheckXmlSetting(txtSettingFile.Text);
                if (xml == null)
                    return;
                DataStructureParser Parser = new DataStructureParser();
                Parser.ShowErrorMessageEvent += new ShowErrorMessage(Parser_ShowErrorMessageEvent);
                if (Parser.Parser(xml) == false) return;
                CreateWinFormFiles.CreateFiles(Parser.BO, txtLocation.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
